<template>
  <view class="favorites-page">
    <!-- 收藏设备列表 -->
    <scroll-view 
      scroll-y 
      class="list-container"
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      @refresherrefresh="onRefresh"
      :refresher-triggered="refreshing"
    >
      <view class="device-list">
        <view 
          v-for="device in favoriteList" 
          :key="device.id"
          class="device-card"
          @click="goToDetail(device.id)"
        >
          <!-- 设备图片 -->
          <view class="device-image-container">
            <image 
              :src="device.images?.[0] || '/static/placeholder-device.png'" 
              class="device-image"
              mode="aspectFill"
            />
            <view class="image-overlay">
              <view class="status-badge" :class="getStatusClass(device.status)">
                {{ getStatusText(device.status) }}
              </view>
              <view class="favorite-btn" @click.stop="removeFavorite(device)">
                <u-icon name="heart-fill" color="#ff6b6b" size="18" />
              </view>
            </view>
          </view>
          
          <!-- 设备信息 -->
          <view class="device-content">
            <view class="device-header">
              <text class="device-title">{{ device.title }}</text>
              <text class="device-brand">{{ device.brand }} {{ device.model }}</text>
            </view>
            
            <view class="device-location" v-if="device.location">
              <u-icon name="map-pin" size="12" color="#888" />
              <text class="location-text">{{ formatLocation(device.location) }}</text>
            </view>
            
            <view class="device-footer">
              <view class="price-section">
                <text class="price-label">日租金</text>
                <text class="price-value">¥{{ device.dailyRent }}</text>
                <text class="price-unit">/天</text>
              </view>
              <view class="favorite-time">
                <text class="time-text">{{ formatTime(device.favoriteCreatedAt) }}收藏</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 加载更多 -->
      <view class="load-more" v-if="hasMore && favoriteList.length > 0">
        <u-loadmore :status="loadStatus" />
      </view>
    </scroll-view>

    <!-- 空状态 -->
    <view v-if="favoriteList.length === 0 && !loading" class="empty-state">
      <image src="/static/empty-favorites.png" class="empty-image" />
      <text class="empty-title">暂无收藏设备</text>
      <text class="empty-desc">去设备列表看看心仪的设备吧</text>
      <u-button type="primary" @click="goToDeviceList">浏览设备</u-button>
    </view>
  </view>
</template>

<script>
import apiService from '@/api/index.js'

export default {
  data() {
    return {
      favoriteList: [],
      totalCount: 0,
      loading: false,
      refreshing: false,
      loadStatus: 'more',
      
      // 分页
      page: 1,
      pageSize: 10,
      hasMore: true
    }
  },
  
  onLoad() {
    this.initPage()
  },
  
  onShow() {
    // 每次显示时刷新列表
    this.loadFavoriteList(true)
  },
  
  methods: {
    async initPage() {
      await this.loadFavoriteList()
    },
    
    async loadFavoriteList(isRefresh = false) {
      if (this.loading) return
      
      try {
        this.loading = true
        this.loadStatus = 'loading'
        
        if (isRefresh) {
          this.page = 1
          this.hasMore = true
        }
        
        const params = {
          page: this.page,
          limit: this.pageSize
        }
        
        console.log('🔍 收藏列表参数:', params)
        
        const response = await apiService.device.getFavoriteList(params)
        console.log('📋 收藏列表响应:', response)
        
        const data = response.data || response
        const devices = data.items || []
        const total = data.total || 0
        
        if (isRefresh) {
          this.favoriteList = devices
        } else {
          this.favoriteList = [...this.favoriteList, ...devices]
        }
        
        this.totalCount = total
        this.hasMore = devices.length === this.pageSize && this.favoriteList.length < total
        
        if (!this.hasMore) {
          this.loadStatus = 'nomore'
        } else {
          this.loadStatus = 'more'
        }
        
        this.page += 1
        
      } catch (error) {
        console.error('加载收藏列表失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
        this.loadStatus = 'more'
      } finally {
        this.loading = false
        this.refreshing = false
      }
    },
    
    // 下拉刷新
    onRefresh() {
      this.refreshing = true
      this.loadFavoriteList(true)
    },
    
    // 加载更多
    loadMore() {
      if (this.hasMore && !this.loading) {
        this.loadFavoriteList()
      }
    },
    
    // 跳转到详情页
    goToDetail(deviceId) {
      uni.navigateTo({
        url: `/pages/devices/detail?id=${deviceId}`
      })
    },
    
    // 取消收藏
    async removeFavorite(device) {
      try {
        await apiService.device.removeFavorite(device.id)
        
        // 从列表中移除
        const index = this.favoriteList.findIndex(item => item.id === device.id)
        if (index !== -1) {
          this.favoriteList.splice(index, 1)
          this.totalCount -= 1
        }
        
        uni.showToast({
          title: '已取消收藏',
          icon: 'success'
        })
        
      } catch (error) {
        console.error('取消收藏失败:', error)
        uni.showToast({
          title: '操作失败',
          icon: 'none'
        })
      }
    },
    
    // 跳转到设备列表
    goToDeviceList() {
      uni.switchTab({
        url: '/pages/devices/list'
      })
    },
    
    // 获取设备状态样式类
    getStatusClass(status) {
      const statusMap = {
        'AVAILABLE': 'available',
        'RENTED': 'rented',
        'MAINTENANCE': 'maintenance',
        'OFFLINE': 'offline'
      }
      return statusMap[status] || 'available'
    },
    
    // 获取设备状态文本
    getStatusText(status) {
      const statusMap = {
        'AVAILABLE': '可租用',
        'RENTED': '已租出',
        'MAINTENANCE': '维护中',
        'OFFLINE': '下线'
      }
      return statusMap[status] || '可租用'
    },
    
    // 格式化位置信息
    formatLocation(location) {
      if (!location) return ''
      if (typeof location === 'object') {
        const { province, city, district } = location
        return `${province || ''}${city || ''}${district || ''}`
      }
      return location
    },
    
    // 格式化时间
    formatTime(timeString) {
      if (!timeString) return ''
      const time = new Date(timeString)
      const now = new Date()
      const diff = now - time
      
      const minute = 60 * 1000
      const hour = 60 * minute
      const day = 24 * hour
      
      if (diff < hour) {
        return Math.floor(diff / minute) + '分钟前'
      } else if (diff < day) {
        return Math.floor(diff / hour) + '小时前'
      } else if (diff < 7 * day) {
        return Math.floor(diff / day) + '天前'
      } else {
        return time.toLocaleDateString()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.favorites-page {
  background: #f5f5f5;
  min-height: 100vh;
}

.list-container {
  height: 100vh;
}

.device-list {
  padding: 0 24rpx;
}

.device-card {
  background: white;
  border-radius: 16rpx;
  margin: 16rpx 0;
  padding: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  display: flex;
  gap: 24rpx;
}

.device-image-container {
  position: relative;
  width: 200rpx;
  height: 150rpx;
  flex-shrink: 0;
}

.device-image {
  width: 100%;
  height: 100%;
  border-radius: 12rpx;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  border-radius: 12rpx;
}

.status-badge {
  position: absolute;
  top: 8rpx;
  left: 8rpx;
  padding: 4rpx 12rpx;
  border-radius: 12rpx;
  font-size: 20rpx;
  color: white;
  
  &.available {
    background: #52c41a;
  }
  
  &.rented {
    background: #faad14;
  }
  
  &.maintenance {
    background: #ff4d4f;
  }
  
  &.offline {
    background: #d9d9d9;
  }
}

.favorite-btn {
  position: absolute;
  top: 8rpx;
  right: 8rpx;
  width: 48rpx;
  height: 48rpx;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.device-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.device-header {
  .device-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    line-height: 1.4;
    margin-bottom: 8rpx;
    display: block;
  }
  
  .device-brand {
    font-size: 24rpx;
    color: #666;
    display: block;
  }
}

.device-location {
  display: flex;
  align-items: center;
  gap: 8rpx;
  
  .location-text {
    font-size: 22rpx;
    color: #888;
  }
}

.device-footer {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  margin-top: auto;
}

.price-section {
  display: flex;
  align-items: baseline;
  gap: 8rpx;
  
  .price-label {
    font-size: 22rpx;
    color: #888;
  }
  
  .price-value {
    font-size: 36rpx;
    font-weight: 600;
    color: #ff6b35;
  }
  
  .price-unit {
    font-size: 24rpx;
    color: #888;
  }
}

.favorite-time {
  .time-text {
    font-size: 20rpx;
    color: #aaa;
  }
}

.load-more {
  padding: 32rpx 0;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 60rpx;
  
  .empty-image {
    width: 240rpx;
    height: 180rpx;
    margin-bottom: 32rpx;
  }
  
  .empty-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 16rpx;
  }
  
  .empty-desc {
    font-size: 28rpx;
    color: #888;
    margin-bottom: 48rpx;
    text-align: center;
    line-height: 1.6;
  }
}
</style>